package com.dogstudio.mygame.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import com.dogstudio.mygame.config.GameColor;
import com.dogstudio.mygame.utils.AppUtils;

/**
 * Created by Administrator on 2016/8/19 0019.
 */

public class Card extends View {
    private Paint mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private int bgColor;
    private int bgCorner = 4;
    private static final int smallTextSize = 30;
    private int textSize = 50;
    private int textColor;
    private int widthSize;
    private int number = 0;

    public Card(Context context) {
        super(context);
        init();
    }

    public Card(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        widthSize = AppUtils.getCardSize(getContext());
        bgColor = GameColor.getCardBgColor(number);
        textColor = GameColor.getCardFontColor(number);
    }

    public void setNumber(int number) {
        this.number = number;
        invalidate();
    }

    public int getNumber() {
        return number;
    }

    public void setDoubleNumber() {
        number = number * 2;
        if (number >= 1024) {
            mTextPaint.setTextSize(smallTextSize);
        }
        invalidate();
    }

    @Override
    public void invalidate() {
        bgColor = GameColor.getCardBgColor(number);
        textColor = GameColor.getCardFontColor(number);
        super.invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(widthSize, widthSize);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 设置圆角背景
        mBgPaint.setColor(bgColor);
        RectF bgRect = new RectF(0, 0, widthSize, widthSize);
        canvas.drawRoundRect(bgRect, bgCorner, bgCorner, mBgPaint);
        // 绘制分数
        if (number > 0) {
            String num = String.valueOf(number);
            mTextPaint.setColor(textColor);
            mTextPaint.setTextSize(textSize);
            Paint.FontMetrics metrics = mTextPaint.getFontMetrics();
            int textWidth = (int) mTextPaint.measureText(num);
            int x = widthSize / 2 - textWidth / 2;
            int y = (int) (widthSize - Math.abs(metrics.descent) + Math.abs(metrics.ascent)) / 2;
            canvas.drawText(String.valueOf(number), x, y, mTextPaint);
        }
    }
}
